using System.Collections.Concurrent;
using CMS.Common;
using CMS.EFCore;
using CMS.Entity;
using CMS.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using Image = SixLabors.ImageSharp.Image;

namespace CMS.Service.Impl;

public partial class ArticleService {
    public async Task<string> UploadFile(IFormFile file, string? waterMark, string path) {
        //创建文件
        string newFileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        string returnDir = Path.Combine("articleImage", DateTime.Now.ToShortDateString());
        string fileDir = Path.Combine(path, returnDir);
        if (!Directory.Exists(fileDir)) {
            Directory.CreateDirectory(fileDir);
        }

        string filePath = Path.Combine(fileDir, newFileName);
        await using var fileStream = File.Create(filePath);
        //处理水印
        if (!string.IsNullOrEmpty(waterMark)) {
            try {
                using var image = Image.Load<Rgba32>(file.OpenReadStream());
                // 加载字体
                var font = SystemFonts.CreateFont("Arial", 20, FontStyle.Bold);
                var watermarkText = "jie ge bu yao";
                var color = Color.White;
                var position = new PointF(10, 10);

                // 添加水印
                image.Mutate(x => x.DrawText(watermarkText, font, color, position));

                // 保存处理后的图像
                await image.SaveAsJpegAsync(fileStream);
            } catch (Exception e) {
                Console.WriteLine(e.Message);
                throw;
            }
        } else {
            await file.CopyToAsync(fileStream);
        }

        return Path.Combine(returnDir, newFileName);
    }

    public async Task CreateStaticHtml(string rootPath, Article article) {
        string outputDir = Path.Combine(rootPath, "ArticleHtml");
        string templatePath = Path.Combine(rootPath, "ArticleTemplate", "ArticleTemplate.hbs");
        await ArticleTemplateHelper.RenderTemplate(templatePath, outputDir, article, article.Id.ToString());
    }

    
}